﻿using Infrastructure.Error;
using Infrastructure.UniOfWorkBase;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;

namespace Domain
{
    public class Monitor : IMonitor
    {
        public int count = 0;
        public ILogger<Monitor> _logger { get; set; }
        public int DoWork(DbContext dbContext, Func<DbContext, int> p)
        {
            if (count >= 64)
            {
                foreach (var entry in dbContext.ChangeTracker.Entries())
                {
                    _logger.LogInformation($"死循环 {Task.CurrentId} Entity:{entry.Entity.GetType().Name},State:{ entry.State.ToString()} Data:{JsonConvert.SerializeObject(entry.Entity)}");
                }
                throw new SystemException("监测到死循环，中止当前任务!");
            }
            count++;

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            int r = p(dbContext);
            stopwatch.Stop();

            if (stopwatch.Elapsed.TotalSeconds >= 2)
            {
                foreach (var entry in dbContext.ChangeTracker.Entries())
                {
                    _logger.LogInformation($"慢SQL ThreadID:{Task.CurrentId} Entity:{entry.Entity.GetType().Name},State:{ entry.State.ToString()} Data:{JsonConvert.SerializeObject(entry.Entity)}");
                }
            }

            return r;
        }
    }
}
